#!/usr/bin/perl
##########################################################################################################################
##### a script to add object permissions for Users of Wigan-Warriors.com
##########################################################################################################################

##########################################################################################################################
######  TODO list  #######################################################################################################
##########################################################################################################################
##########################################################################################################################

##########################################################################################################################
###### Bug list
##########################################################################################################################
##########################################################################################################################

##########################################################################################################################
# Includes
##########################################################################################################################

use lib qw(../cgi-bin);
use DBI;
use WiganRL;
use WiganRL::DataObject::Squad;
use WiganRL::DataObject::News;
use WiganRL::DataObject::View;
use WiganRL::DataObject::Image;
use WiganRL::DataObject::Player;
use WiganRL::DataObject::Matchstats;
use WiganRL::DataObject::Injury;
use Carp;

use Getopt::Long;

use strict;
#use warnings;
local $SIG{__WARN__} = \&Carp::cluck;  #full call back trace

$|++;  #unbuffered

##########################################################################################################################
# get arguments
##########################################################################################################################

my $daily= '';
my $weekly= '';
my $none= '';
GetOptions ('daily' => \$daily, 'weekly' => \$weekly, 'none' => \$none);

##########################################################################################################################
# site setup and location variable declarations
##########################################################################################################################
my $cfg= WiganRL::DataObject->load_config('../cgi-bin/wiganrl.ini');
WiganRL::DataObject->cgi_base_url("http://www.wiganwarriorsfans.com".$cfg->val('paths', 'CGI_BASE_URL'));
WiganRL::DataObject->site_base_url("http://www.wiganwarriorsfans.com".$cfg->val('paths', 'SITE_BASE_URL'));
WiganRL::DataObject->site_base_dir($cfg->val('paths', 'SITE_BASE_DIR'));
#WiganRL::DataObject->cachedir($cfg->val('paths', 'SITE_BASE_DIR')."/cached");
WiganRL::DataObject->datadir($cfg->val('paths', 'SITE_DATA_DIR'));
WiganRL::DataObject->template_dir($cfg->val('paths', 'SITE_BASE_DIR')."/templates");
WiganRL::DataObject->dataurl('data');

WiganRL::DataObject->email_dir($cfg->val('emails', 'EMAIL_BASE_DIR'));
WiganRL::DataObject->smtpserver($cfg->val('emails', 'EMAIL_SMTP_SERVER'));
WiganRL::DataObject->smtpusername($cfg->val('emails', 'EMAIL_SMTP_USERNAME'));
WiganRL::DataObject->smtppassword($cfg->val('emails', 'EMAIL_SMTP_PASSWORD'));
WiganRL::DataObject->email_from($cfg->val('emails', 'EMAIL_FROM'));
WiganRL::DataObject->email_replyto($cfg->val('emails', 'EMAIL_REPLYTO'));
WiganRL::DataObject->send_emails($cfg->val('emails', 'SEND_EMAILS'));
WiganRL::DataObject->email_debug($cfg->val('emails', 'EMAIL_DEBUG_MODE'));
WiganRL::DataObject->email_debuguser($cfg->val('emails', 'EMAIL_DEBUG_USER'));
#WiganRL::DataObject->email_debug(1);

my $cgi= CGI::Simple->new();

my $dbh= Diva::DB->new();
$dbh->set( {
	DATABASE_NAME       => $cfg->val('database', 'DATABASE_NAME'),
	DATABASE_SERVER     => $cfg->val('database', 'DATABASE_SERVER'),
	DATABASE_USERNAME   => $cfg->val('database', 'DATABASE_USERNAME'),
	DATABASE_PASSWORD   => $cfg->val('database', 'DATABASE_PASSWORD'),
	DATABASE_TYPE       => $cfg->val('database', 'DATABASE_TYPE'),
	} );
$dbh->connect();

WiganRL::DataObject->dbh($dbh);
WiganRL::Search->dbh($dbh);
WiganRL::DataObject->init_class('WWCOM');  #loads contenttypes
WiganRL::DataObject->cgi($cgi);

WiganRL::DataObject->user(WiganRL::DataObject::User->new($cfg->val('site','SITE_ADMINUSER')));

#empty session
use CGI::Session;
CGI::Session->name('wrSID');
WiganRL::DataObject->session(CGI::Session->new);

##########################################################################################################################
# setup page object
##########################################################################################################################
my $page= WiganRL::DataObject::Page->new();
$cgi->param('CGI_BASE_URL',WiganRL::DataObject->cgi_base_url.'?');
$cgi->param('SITE_BASE_URL',WiganRL::DataObject->site_base_url);

#set page style
$cgi->cookie('wrStyle') ne '' ? 
	$cgi->param('STYLE',$cgi->cookie('wrStyle')) :
	$cgi->param('STYLE','2010home');

#set BB style
$cgi->param('BBSTYLE',$cgi->param('STYLE'));
WiganRL::DataObject->bbstyle($cfg->val('forums','BBSTYLE_ROOT_URL').$cgi->param('BBSTYLE'));
#WiganRL::setupPage($page);

	#setup right margin withtop content
	my $o= WiganRL::DataObject->new;
	for (@{WiganRL::DataObject::News->top_content(5)}) {
		$o->add_object($_,"News.Related.html");
	}
	$page->rightmargin->add_object($o,"News.RightMargin.TopStories.html");
	$page->rightmargin->add_object($o,"Divider.html");
	
	$o= WiganRL::DataObject->new;
	for (@{WiganRL::DataObject::Viewtopic->top_content(5)}) {
		$o->add_object($_,"Viewtopic.Related.html");
	}
	$page->rightmargin->add_object($o,"Viewtopic.RightMargin.TopTopics.html");
	$page->rightmargin->add_object($o,"Divider.html");
	$page->rightmargin->template("Objects.html");
	
	$page->param('PAGE_TITLE','Update Email');
	$page->set_content_title('New and Updated Content');
	$page->set_rightmargin_title('&nbsp;');


#open log file
#open LOG, ">>wiganrl_updates.log";
#print LOG "\n\nRunning wiganrl_updates.pl\n\n";


my $count= 0;
my $viewcount= 0;
my $view= undef;
if ($daily || $weekly || $none) {

	my $htmlObject= WiganRL::DataObject->new;
	my $txtObject= WiganRL::DataObject->new;

	my $htmlTemplates= { 'NEWS' => "News.Snip.html",
		'VIEWTOPIC' => 'Viewtopic.Snip.html',
		'IMAGE' => 'Image.Snip.html',
		'PLAYER' => 'Player.Snip.html',
		'MATCHSTATS' => 'Matchstats.Snip.html',
		'INJURY' => 'Injury.Snip.html'
	};

	my $txtTemplates= { 'NEWS' => WiganRL::DataObject->email_dir."/updates/News.Snip.txt",
		'VIEWTOPIC' => WiganRL::DataObject->email_dir.'/updates/Viewtopic.Snip.txt',
		'IMAGE' => WiganRL::DataObject->email_dir.'/updates/Image.Snip.txt',
		'PLAYER' => WiganRL::DataObject->email_dir.'/updates/Player.Snip.txt',
		'MATCHSTATS' => WiganRL::DataObject->email_dir.'/updates/Matchstats.Snip.txt',
		'INJURY' => WiganRL::DataObject->email_dir.'/updates/Injury.Snip.txt'
	};

    #get new content
    my $s= WiganRL::Search->new;
    for ('NEWS','VIEWTOPIC','IMAGE','PLAYER','MATCHSTATS','INJURY') {
        $s->table($_);
        $s->where("OBJECT_DATE > (NOW() - INTERVAL 1 DAY) and OBJECT_LINKABLE='True'") if ($daily);
        $s->where("OBJECT_DATE > (NOW() - INTERVAL 7 DAY) and OBJECT_LINKABLE='True'") if ($weekly);
        $s->orderby('OBJECT_NVIEWS desc');
        $s->limit(5);
        for (@{$s->search}) {
            print "Found Object: ".$_->type." (".$_->id.")\n";
 #           print LOG "Found Object: ".$_->type." (".$_->id.")\n";
            $htmlObject->add_object($_,$htmlTemplates->{$_->type});
            $txtObject->add_object($_,$txtTemplates->{$_->type});
            $count++;
        }
    }

    #now do modified objects
    for ('VIEWTOPIC','MATCHSTATS','INJURY') {
        $s->table($_);
        $s->where("OBJECT_MODIFIED_DATE > (NOW() - INTERVAL 1 DAY) and OBJECT_LINKABLE='True'") if ($daily);
        $s->where("OBJECT_MODIFIED_DATE > (NOW() - INTERVAL 7 DAY) and OBJECT_LINKABLE='True'") if ($weekly);
        $s->orderby('OBJECT_NVIEWS desc');
        $s->limit(5);
        for my $m (@{$s->search}) {
            print "Found Modified Object: ".$m->type." (".$m->id.")\n";
  #          print LOG "Found Modified Object: ".$m->type." (".$m->id.")\n";
            my $found= 0;
            for my $o (@{$page->objects}) {
                if ($o->{Object}->id == $m->id) {
                    $found++;
                    last;
                }
            }
            $htmlObject->add_object($m,$htmlTemplates->{$_}) if (!$found);
            $txtObject->add_object($m,$txtTemplates->{$_}) if (!$found);
            $count++;
        }
    }

    if ($count <= 0) {
        print "No content or only views found";
   #     print LOG "No content or only views found";
   #     close LOG;
        exit(1);
    }
	$htmlObject->template('Objects.html');
	$txtObject->template('Objects.html');
	$page->param('HTML_OBJECT_OUTPUT',$htmlObject->output);
	$page->param('TXT_OBJECT_OUTPUT',$txtObject->output);

#    if ($viewcount>0 && defined $view) {
#        $view->param('VIEW_COUNT',$viewcount);
#        $page->add_object($view);
#    }

    #then get all users
    my $users;
    if ($daily) {
        my $s= WiganRL::Search->new;
        $s->table('USER'); $s->where("USER_UPDATES = 'Daily' and USER_ACTIVE='True'");
        $users= $s->search;
    } elsif ($weekly) {
        my $s= WiganRL::Search->new;
        $s->table('USER'); $s->where("USER_UPDATES = 'Weekly' and USER_ACTIVE='True'");
        $users= $s->search;
    } else {
        my $s= WiganRL::Search->new;
        $s->table('USER'); $s->where("PK_USER_ID = 1");
        $users= $s->search;
    }
	my @emails;
	my $nemails= 0;
    for (@$users) {
        if (!WiganRL::DataObject->email_debug || 
				(WiganRL::DataObject->email_debug && $nemails<10)) {
            print "Sending to USER: ".$_->id." (".$_->param('USER_NAME')." <".$_->param('USER_EMAIL').">)\n";
#            print LOG "Sending to USER: ".$_->id." (".$_->param('USER_NAME')." <".$_->param('USER_EMAIL').">)\n";

			WiganRL::DataObject->user($_);
			$page->setupPage;

			push @emails,$page->buildemail('Wigan-Warriors.com Update',$page->email_dir."/updates/User.Update",
				$_->param('USER_NAME'),$_->param('USER_EMAIL'));
			$nemails++;
        }
    }
	#now send the emails
#	print $page->output($page->email_dir.'/updates/User.Update.html');
#	carp "got here";
	$page->sendemails(\@emails);
#	carp "got here too";

} else {
    print "No arguments specified\n";
#    print LOG "No arguments specified\n";
}

#close LOG;

$page->finish;
exit(0);
